﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcDatagrid.Models;
using System.Configuration;
using System.IO;

namespace MvcDatagrid.Controllers
{
    public class OrderController : Controller
    {
        private NorthwindEntities db = new NorthwindEntities();

        //
        // GET: /Order/
       
        public ActionResult Index()
        {
            var orders = db.Orders.Include("Customers").Include("Employees").Include("Shippers");
            return View(orders.ToList());
        }

        //
        // GET: /Order/Details/5

        public ActionResult Details(int id = 0)
        {
            Orders orders = db.Orders.Single(o => o.OrderID == id);
            if (orders == null)
            {
                return HttpNotFound();
            }
            return View(orders);
        }

        //
        // GET: /Order/Create

        public ActionResult Create()
        {
            ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CompanyName");
            ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "LastName");
            ViewBag.ShipVia = new SelectList(db.Shippers, "ShipperID", "CompanyName");
            return View();
        }

        //
        // POST: /Order/Create

        [HttpPost]
        public ActionResult Create(Orders orders)
        {
            if (ModelState.IsValid)
            {
                db.Orders.AddObject(orders);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CompanyName", orders.CustomerID);
            ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "LastName", orders.EmployeeID);
            ViewBag.ShipVia = new SelectList(db.Shippers, "ShipperID", "CompanyName", orders.ShipVia);
            return View(orders);
        }

        //
        // GET: /Order/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Orders orders = db.Orders.Single(o => o.OrderID == id);
            if (orders == null)
            {
                return HttpNotFound();
            }
            ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CompanyName", orders.CustomerID);
            ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "LastName", orders.EmployeeID);
            ViewBag.ShipVia = new SelectList(db.Shippers, "ShipperID", "CompanyName", orders.ShipVia);
            return View(orders);
        }

        //
        // POST: /Order/Edit/5

        [HttpPost]
        public ActionResult Edit(FormCollection form)
        {
            int id = Convert.ToInt32(form["OrderId"]);
            Orders orders = db.Orders.Single(o => o.OrderID == id);
            orders.ShipCity = form["ShipCity"].ToString();
            orders.ShipCountry = form["ShipCountry"].ToString();
            orders.ShipPostalCode = form["ShipPostalCode"].ToString();
            orders.ShipAddress = form["ShipAddress"].ToString() ?? orders.ShipAddress;
            if (ModelState.IsValid)
            {
                db.ObjectStateManager.ChangeObjectState(orders, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            //ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CompanyName", orders.CustomerID);
            //ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "LastName", orders.EmployeeID);
            //ViewBag.ShipVia = new SelectList(db.Shippers, "ShipperID", "CompanyName", orders.ShipVia);
            return View(orders);
        }

        //
        // GET: /Order/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Orders orders = db.Orders.Single(o => o.OrderID == id);
            if (orders == null)
            {
                return HttpNotFound();
            }
            return View(orders);
        }

        //
        // POST: /Order/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Orders orders = db.Orders.Single(o => o.OrderID == id);
            db.Orders.DeleteObject(orders);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        public ActionResult GridView()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DisplayGridView(string sidx, string sord, int rows, int page)
        {
            var orders = db.Orders;
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = orders.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
            var ordersToDisplay = orders.OrderBy("it." + sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);

            return Json(new
            {
                total = totalPages, 
                page = page,
                records = totalRecords,
                rows = (from p in ordersToDisplay
                        select new
                        {
                            OrderID = p.OrderID,
                            CustomerID = p.CustomerID,
                            EmployeeID = p.EmployeeID,
                            OrderDate = p.OrderDate,
                            RequiredDate = p.RequiredDate,
                            Freight = p.Freight,
                            ShippedDate = p.ShippedDate,
                            ShipVia = p.ShipVia,
                            ShipName = p.ShipName,
                            ShipAddress = p.ShipAddress,
                            ShipCity = p.ShipCity,
                            ShipRegion = p.ShipRegion,
                            ShipPostalCode = p.ShipPostalCode,
                            ShipCountry = p.ShipCountry
                        })
            });
        }
        /// <summary>
        /// Persist the file to disk.
        /// </summary>
        private string UploadFile(HttpPostedFileBase file)
        {
            // Initialize variables we'll need for resizing and saving
            // Build absolute path
            var absPath = @"C:\path\to\file\";
            var absFileAndPath = string.Format("{0}{1}",absPath, file.FileName);

            // Create directory as necessary and save image on server
            if (!Directory.Exists(absPath))
                Directory.CreateDirectory(absPath);
            file.SaveAs(absFileAndPath);

            // Resize image using "ImageResizer" NuGet package.
            //var width = int.Parse(ConfigurationManager.AppSettings["AuthorThumbnailResizeWidth"]);
            //var height = int.Parse(ConfigurationManager.AppSettings["AuthorThumbnailResizeHeight"]);
            //var resizeSettings = new ImageResizer.ResizeSettings
            //{
            //    Scale = ImageResizer.ScaleMode.DownscaleOnly,
            //    Width = width,
            //    Height = height,
            //    Mode = ImageResizer.FitMode.Crop
            //};
            //var b = ImageResizer.ImageBuilder.Current.Build(absFileAndPath, resizeSettings);

            // Save resized image
            //b.Save(absFileAndPath);

            // Return relative file path
            return file.FileName;
            //return relativeFileAndPath;
        }
        [HttpPost]
        public ActionResult UploadManyFilesAction()
        {
            // Validate we have a file being posted
            if (Request.Files.Count == 0)
            {
                return Json(new { statusCode = 500, status = "No image provided." }, "text/html");
            }

            // File we want to resize and save.
            var file = Request.Files[0];

            try
            {
                var filename = UploadFile(file);

                // Return JSON
                return Json(new
                {
                    statusCode = 200,
                    status = "Image uploaded.",
                    file = filename,
                }, "text/html");
            }
            catch (Exception ex)
            {
                // Log using "NLog" NuGet package
                //Logger.ErrorException(ex.ToString(), ex);
                return Json(new
                {
                    statusCode = 500,
                    status = "Error uploading image.",
                    file = string.Empty
                }, "text/html");
            }
        }

        public ActionResult UploadFiles() {
            return View();
        }
        
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}